package com.example.flowabledemo.listener;

import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @ClassName: MultiTaskCompleteListener
 * @Description:
 * @Date 2024/05/27 10:05
 * @Author songshaoqiu
 **/
@Component
public class MultiTaskCompleteListener implements TaskListener {
    private static final Logger logger = LoggerFactory.getLogger(MultiTaskCompleteListener.class);
    @Override
    public void notify(DelegateTask delegateTask) {
        System.out.println("自定义监听器执行了，任务名称为：" + delegateTask.getName());
        if (EVENTNAME_COMPLETE.equals(delegateTask.getEventName())) {
            System.out.println("任务完成了");
        }
        Object result = delegateTask.getVariable("result");
        if (result.equals(0)) {
            logger.info("当前任务（{}）有人审批不通过，结束会签任务", delegateTask.getName());
            delegateTask.setVariable("approve", "finished");
            return;
        }
        if (!result.equals(1)) {
            throw new IllegalArgumentException("不识别的流程变量取值: " + result);
        }
        Integer nrOfInstances = (Integer) delegateTask.getVariable("nrOfInstances");
        logger.info("任务会签总数：" + nrOfInstances);
        logger.info("待会签任务数量：" + delegateTask.getVariable("nrOfActiveInstances"));
        logger.info("已完成会签任务数量：" + delegateTask.getVariable("nrOfCompletedInstances"));

        //获取同意人数
        Object agreeObj = delegateTask.getVariable("agree");
        if (agreeObj == null) {
            delegateTask.setVariable("agree", 1);
            logger.info("当前同意人数为{}, 增加同意人数为：{}", 0, 1);
        } else {
            delegateTask.setVariable("agree", (Integer) agreeObj + 1);
            logger.info("当前同意人数为{}, 增加同意人数为：{}", agreeObj, (Integer) agreeObj + 1);
        }
        // 最终的同意人数
        Integer agree = (Integer) delegateTask.getVariable("agree");
        logger.info("当前审批通过的人数: {}", delegateTask.getVariable("agree"));
        if (agree.equals(nrOfInstances)) {
            logger.info("审批通过的人数（{}）为达到任务会签总数（{}），结束会签任务（{}）", agree, nrOfInstances, delegateTask.getName());
            delegateTask.setVariable("approve", "finished");
            return;
        }
        logger.info("当前审批通过的人数（{}），还未达到任务会签总数（{}），继续会签任务（{}）", agree, nrOfInstances, delegateTask.getName());
        delegateTask.setVariable("approve", "unfinished");
    }
}
